package com.uwlaser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.uwlaser.config.FileProperties;
import com.uwlaser.domain.DeviceMain;
import com.uwlaser.exception.BadRequestException;
import com.uwlaser.service.mapper.DeviceMainMapper;
import com.uwlaser.utils.FileUtil;
import com.uwlaser.utils.enums.DictValueEnum;
import lombok.AllArgsConstructor;
import com.uwlaser.base.PageInfo;
import com.uwlaser.base.QueryHelpMybatisPlus;
import com.uwlaser.base.impl.CommonServiceImpl;
import com.uwlaser.utils.ConvertUtil;
import com.uwlaser.utils.PageUtil;
import com.uwlaser.domain.DeviceFile;
import com.uwlaser.service.DeviceFileService;
import com.uwlaser.service.dto.DeviceFileDto;
import com.uwlaser.service.dto.DeviceFileQueryParam;
import com.uwlaser.service.mapper.DeviceFileMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

/**
* @author zk-Qin
* @date 2022-05-11
*/
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = DeviceFileService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DeviceFileServiceImpl extends CommonServiceImpl<DeviceFileMapper, DeviceFile> implements DeviceFileService {

    // private final RedisUtils redisUtils;
    private final DeviceFileMapper deviceFileMapper;

    private final DeviceMainMapper deviceMainMapper;

    private final FileProperties properties;

    @Override
    public PageInfo<DeviceFileDto> queryAll(DeviceFileQueryParam query, Pageable pageable) {
        IPage<DeviceFile> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<DeviceFile> page = deviceFileMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(page, DeviceFileDto.class);
    }

    @Override
    public List<DeviceFileDto> queryAll(DeviceFileQueryParam query){
        return ConvertUtil.convertList(deviceFileMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), DeviceFileDto.class);
    }

    @Override
    public DeviceFile getById(Integer id) {
        return deviceFileMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public DeviceFileDto findById(Integer id) {
        return ConvertUtil.convert(getById(id), DeviceFileDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(DeviceFileDto resources) {
        DeviceFile entity = ConvertUtil.convert(resources, DeviceFile.class);
        return deviceFileMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(DeviceFileDto resources){
        DeviceFile entity = ConvertUtil.convert(resources, DeviceFile.class);
        int ret = deviceFileMapper.updateById(entity);
        // delCaches(resources.id);
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<Integer> ids){
        List<DeviceFile> deviceFiles = deviceFileMapper.selectList(new LambdaQueryWrapper<DeviceFile>().in(DeviceFile::getId, ids));
        for (DeviceFile deviceFile : deviceFiles) {

            //如果是删除图片更新主表设备头像字段
            if(deviceFile.getAppType().equals(DictValueEnum.DEVICE_FILE_TYPE_IMG.getValue())){
                DeviceMain deviceMain = new DeviceMain();
                deviceMain.setId(deviceFile.getDeviceId());
                deviceMain.setPicture("");
                deviceMainMapper.updateById(deviceMain);
            }
            //删除系统文件
            FileUtil.del(deviceFile.getDiskPath());
        }
        // delCaches(ids);
        return deviceFileMapper.deleteBatchIds(ids);
    }

    /**
     * 上传文件
     * @param multipartFile
     * @param resources
     * @return
     */
    @Override
    public int insert(MultipartFile multipartFile, DeviceFileDto resources) {
        DeviceFile deviceFile = ConvertUtil.convert(resources, DeviceFile.class);
        // 文件大小验证
        FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
        // 验证文件上传的格式
        String image = "gif jpg png jpeg csv doc dot json mp2 mp3 mp4 mpeg mpg mpp pdf ppt rtf txt wdb wps xls xlsx xlt xlw zip";
        String fileType = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        if(fileType != null && !image.contains(fileType)){
            throw new BadRequestException("文件格式错误！, 仅支持 " + image +" 格式");
        }
        String filePath = "files\\";
        File file = FileUtil.upload(multipartFile, properties.getPath().getDevice() + filePath);
        deviceFile.setFileName(file.getName());
        deviceFile.setOriginalFileName(multipartFile.getOriginalFilename());
        deviceFile.setDiskPath(Objects.requireNonNull(file).getPath());
        deviceFile.setSuffix(fileType);
        deviceFile.setVisitPath("device\\" + filePath + file.getName());
        deviceFile.setAppType(DictValueEnum.DEVICE_FILE_TYPE_FILE.getValue());
        return deviceFileMapper.insert(deviceFile);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(Integer id){
        Set<Integer> set = new HashSet<>(1);
        set.add(id);
        return this.removeByIds(set);
    }

    /*
    private void delCaches(Integer id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<Integer> ids) {
        for (Integer id: ids) {
            delCaches(id);
        }
    }*/

    /*
    @Override
    public void download(List<DeviceFileDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (DeviceFileDto deviceFile : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("设备id", deviceFile.getDeviceId());
              map.put("磁盘路径", deviceFile.getDiskPath());
              map.put("访问路径", deviceFile.getVisitPath());
              map.put("原文件名", deviceFile.getOriginalFileName());
              map.put("文件名", deviceFile.getFileName());
              map.put("应用类型", deviceFile.getAppType());
              map.put("后缀", deviceFile.getSuffix());
              map.put("创建人", deviceFile.getCreateBy());
              map.put("创建时间", deviceFile.getCreateTime());
              map.put("更新人", deviceFile.getUpdateBy());
              map.put("更新时间", deviceFile.getUpdateTime());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/
}
